package fr.web325.servlet.api.user;

import fr.web325.bean.Json;
import fr.web325.bean.User;
import fr.web325.dao.UserDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/api/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = null;
        try {
            user = new UserDao().Login(req.getParameter("username"), req.getParameter("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(user==null){
            resp.getWriter().print(new Json(200,null,"账户或密码错误,请重试!").getRespJson());
            return;
        }
        // 未激活,提示到邮箱中激活
        if(user.getState() == 0){
            resp.getWriter().print(new Json(200,null,"请到注册的邮箱进行激活后在登录,邮箱号"+user.getEmail()).getRespJson());
            return;
        }
        //将数据存储到session中
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        session.setAttribute("cart", null);
        session.setMaxInactiveInterval(60*60*24);
        JSONObject userJson = JSONObject.fromObject(user);
        resp.getWriter().print(new Json(200,userJson,"登陆成功！").getRespJson());

    }
}
